/*
 * @lc app=leetcode.cn id=92 lang=java
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(head == null || head.next == null || left == right) {
            return head;
        }

        ListNode dummy = new ListNode(0, head);
        ListNode p = dummy;
        for(int i = 0; i < left - 1; i++) {
            p = p.next;
        }

        ListNode pre = null;
        ListNode cur = p.next;

        for(int i = 0; i < right - left + 1; i++) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }

        p.next.next = cur;
        p.next = pre;

        return dummy.next;


    }
}
// @lc code=end

